import pinyingMatch from 'pinyin-match'
import { store } from 'store'

type Result = {
  list: Category[]
  message: string
}

// 获取/查询符号列表
export const getSignListAPI = (keywords?: string) => {
  return new Promise<Array<Category>>(async (resolve, reject) => {
    const { onlineStatus } = store.getState().system

    if (onlineStatus) {
      // 在线模式
      const res: Result = await fetch(process.env.REACT_APP_BASE_URL + '/sign/list').then(res => res.json())
      resolve(res.list)
    } else {
      // 离线模式
      const signList = await getSignList<Sign>()
      if (keywords?.trim()) {
        const lowerKeywords = keywords.toLowerCase()
        const result: Category = {
          id: 50,
          categoryNameZh: '关键字搜索结果',
          categoryNameEn: 'keywordsResult',
          children: []
        }
        signList.forEach(sign => {
          // 拼音匹配成功或包含相应关键字都算查找成功
          if (pinyingMatch.match(sign.signKeywords, lowerKeywords) || sign.signKeywords.includes(lowerKeywords)) {
            result.children!.push(sign)
          }
        })
        resolve([result])
      } else {
        const categoryList = await getCategoryListAPI<Category>()
        const categorySignList = await getCategorySignList<{ categoryId: number; signId: number }>()
        categoryList.forEach(item => {
          item.children = []
          categorySignList.forEach(val => {
            if (val.categoryId === item.id) {
              const findSign = signList.find(v => v.id === val.signId)
              findSign && item.children?.push(findSign)
            }
          })
        })
        resolve(categoryList)
      }
    }
  })
}

// 获取类别列表
export const getCategoryListAPI = <T>() => {
  return new Promise<Array<T>>(async (resolve, reject) => {
    const { onlineStatus } = store.getState().system

    if (onlineStatus) {
      try {
        const res: T[] = await fetch(process.env.REACT_APP_BASE_URL + '/sign/categories').then(res => res.json())
        resolve(res)
      } catch (err) {
        console.warn(err)
      }
    } else {
      fetch('database/t_category.json')
        .then(async result => {
          const res: T[] = await result.json()
          resolve(res)
        })
        .catch(err => {
          reject(new Error(err))
        })
    }
  })
}

// 获取符号列表
export const getSignList = <T>() => {
  return new Promise<Array<T>>((resolve, reject) => {
    fetch('database/t_sign.json')
      .then(async result => {
        const res: T[] = await result.json()
        const { signList } = store.getState().sign
        resolve([...(signList as T[]), ...res])
      })
      .catch(err => {
        reject(new Error(err))
      })
  })
}

// 查询单个符号信息
export const getSignInfoAPI = async (id: number) => {
  const { onlineStatus } = store.getState().system
  if (onlineStatus) {
    return {
      data: {}
    }
  } else {
    const signList = store.getState().sign.signList
    const signInfo = signList.find(item => item.id === id)
    return {
      data: signInfo
    }
  }
}

// 获取中间表
export const getCategorySignList = <T>() => {
  return new Promise<Array<T>>((resolve, reject) => {
    fetch('database/t_category_sign.json')
      .then(async result => {
        const res: T[] = await result.json()
        const { signList } = store.getState().sign
        const storeCategorySignList = signList.map(item => ({ categoryId: item.categoryId, signId: item.id }))
        resolve([...res, ...(storeCategorySignList as T[])])
      })
      .catch(err => {
        reject(new Error(err))
      })
  })
}
